// pages/my/car/index.js
const app = getApp()
const {
  navBarHeight,
  statusBarHeight,
  menuButton
} = app.globalData
const {
  baseURL
} = require('../../../fetch/http')
const api = require('../../../fetch/api')
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseURL: baseURL,
    statusBarHeight: statusBarHeight,
    h: navBarHeight,
    w: menuButton.width,
    right: menuButton.right,
    bottomHeight: navBarHeight - statusBarHeight,
    arr: [],
    loading: false,
    finished: false,
    page: 1,
    sum: 0, // 总计
    isSelectedAll: false, // 是否全选
    isEdit: false // 是否为编辑状态
  },
  back() {
    wx.navigateBack()
  },
  pay() {
    let arr = this.data.arr.filter(n=>n.selected)
    let str = arr.map(n=>n.id).join(',')
    // console.log(str);
    wx.navigateTo({
      url: '/pages/my/settle/index?id=' + str,
    })
  },
  toggleState() {
    let { isEdit } = this.data
    this.setData({
      isEdit: !isEdit
    })
  },
  async add(e) {
    const { index, id } = app.dataSet(e)
    let item = this.data.arr[index]
    // 当前数量小于库存量 
    if(item.num < item.sku){
      item.num++
    }else {
      app.toast('库存不足')
      return
    }
    let res = await api.cartChange({
      cart_id: id,
      num: item.num
    })
    this.setData({
      [`arr[${index}].num`]:item.num
    })
    this.computedSum()
  },
  async reduce(e) {
    const { index, id } = app.dataSet(e)
    let item = this.data.arr[index]
    if(item.num == 1 ){
      // app.toast('最少购买一件哦～')
      return
    }
    item.num--
    let res = await api.cartChange({
      cart_id: id,
      num: item.num
    })
    this.setData({
      [`arr[${index}].num`]:item.num
    })
    this.computedSum()
  },
  async remove() {
    let array = this.data.arr.filter(item=>item.selected)
    Dialog.confirm({
      title: `确认要删除${array.length}件商品吗？`,
      message: '点击确认继续',
    })
      .then(() => {
        api.cartDel({
          cart_id: array.map(n=>n.id)
        }).then(res=>{
          this.clear()
          this.cart()
          this.computedSum()
        })
      })
      .catch(() => {
        // on cancel
      });
  },
  // 判断是否全选
  isSelectedAll() {
    let flag = true // 默认全选
    let array = this.data.arr
    for (let index = 0; index < array.length; index++) {
      const element = array[index];
      if (element.selected === false) {
        flag = false;
        break;
      }
    }
    this.setData({
      isSelectedAll: flag
    })
  },
  // 计算总金额
  computedSum() {
    let arr = this.data.arr.filter(n=>n.selected)
    let sum = arr.reduce((accumulator,currentValue)=>{
      if(currentValue.selected) {
        return accumulator + (currentValue.num * currentValue.price*100)
      }else {
        return accumulator
      }
    },0)
    this.setData({
      sum: (sum/100).toFixed(2)
    })
  },
  // 全选/全不选
  toggleSelectedAll() {
    let {
      isSelectedAll
    } = this.data
    this.setData({
      isSelectedAll: !isSelectedAll
    })
    let array = [...this.data.arr]
    for (let index = 0; index < array.length; index++) {
      const element = array[index];
      element.selected = !isSelectedAll
    }
    this.setData({
      arr: array
    })
    this.computedSum()
  },
  async toggle(e) {
    const {
      index,
      id
    } = app.dataSet(e)
    let item = this.data.arr[index]
    this.setData({
      [`arr[${index}].selected`]: !item.selected
    })
    this.isSelectedAll()
    this.computedSum()
  },
  async cart() {
    if (!this.data.loading) {
      this.setData({
        loading: true
      })
      let res = await api.cart({
        page: this.data.page,
      })
      let newArr = res.data.map(n => {
        n.selected = false
        return n
      })
      let finished = false
      res.data.length == 0 && (finished = true)
      this.setData({
        arr: [...this.data.arr, ...newArr],
        finished,
        loading: false
      })
    }
  },
  clear() {
    this.setData({
      page: 1,
      loading: false,
      finished: false,
      arr: []
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.clear()
    this.cart()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})